/// 简化的兼容性层 - 仅使用Go实现
/// 提供向后兼容的API，让现有代码能够平滑过渡到纯Go架构

import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../config/app_config.dart';
import 'app_services.dart';
import 'simple_tunnel_manager.dart';

/// 隧道实现类型（仅保留Go实现）
enum TunnelImplementation {
  simple,    // 简化Go实现 - 唯一选项
}

/// 兼容旧的AppService接口 - 纯Go实现
class AppService {
  static final _container = ProviderContainer();
  
  // 配置选项：仅使用Go实现
  static TunnelImplementation _implementation = TunnelImplementation.simple;
  
  /// 设置使用的实现类型（仅支持简化Go实现）
  static void setImplementation(TunnelImplementation implementation) {
    _implementation = TunnelImplementation.simple; // 强制使用简化Go实现
    print('🔧 隧道实现: 简化Go实现 (唯一选项)');
  }
  
  /// 兼容性方法 - 设置Go/Dart实现（现在只支持Go）
  static void setImplementationLegacy({required bool useGo}) {
    setImplementation(TunnelImplementation.simple); // 总是使用Go实现
  }
  
  /// 检查当前使用的实现
  static TunnelImplementation get currentImplementation => TunnelImplementation.simple;
  
  /// 兼容性方法 - 检查是否使用Go实现（总是返回true）
  static bool get isUsingGoImplementation => true;

  /// 初始化服务
  Future<void> initialize() async {
    // 新架构中初始化是自动的，这里保持兼容性
  }

  /// 创建并连接隧道 - 纯Go实现
  Future<TunnelData> createAndConnectTunnel({
    required String serverName,
    required String localHost,
    required String localPort,
  }) async {
    print('🚀 创建隧道连接...');
    print('   服务名: $serverName');
    print('   本地地址: $localHost:$localPort');
    
    // 1. 调用API创建隧道
    final tunnelRepository = _container.read(tunnelRepositoryProvider);
    final apiResult = await tunnelRepository.createTunnel(
      serverName: serverName,
      localHost: localHost,
      localPort: localPort,
    );
    
    if (apiResult.isFailure) {
      final failure = apiResult.failureOrNull!;
      throw Exception('创建隧道失败: ${failure.message}');
    }
    
    final result = apiResult.dataOrNull!;
    
    // 2. 创建 TunnelData 对象
    final appConfig = AppConfig.instance;
    final tunnelData = TunnelData(
      tunnelId: result.tunnelId,
      serverName: serverName,
      localHost: localHost,
      localPort: localPort,
      tunnelHost: result.tunnelHost,
      tunnelPort: result.tunnelPort,
      publicPort: result.publicPort,
      publicAddress: 'http://${result.tunnelId.split('-').first}.${appConfig.defaultDomain}',
      tunnelType: 'http',
    );

    // 3. 仅使用简化Go实现建立TCP连接，传递真实的隧道ID
    try {
      final success = await SimpleTunnelService.createTunnel(
        serverName: serverName,
        localHost: localHost,
        localPort: localPort,
        tunnelId: result.tunnelId, // 使用服务器返回的真实隧道ID
        onStateChange: (state, message) {
          print('🔄 Go隧道状态变化通知: $state - $message');
          // TODO: 这里需要通知UI更新状态
          // 可以通过EventBus、Provider或其他状态管理方式通知UI
        },
        onError: (error) {
          print('❌ Go隧道错误通知: $error');
          // TODO: 这里需要通知UI显示错误状态
        },
      );

      if (!success.success) {
        throw Exception('Go隧道连接失败: ${success.error}');
      }

      print('🚀 使用简化Go实现建立TCP连接: ${result.tunnelId}');
    } catch (e) {
      print('❌ Go实现失败，无回退选项: $e');
      throw Exception('Go隧道连接失败，请检查Go动态库: $e');
    }

    // 4. 异步更新数据库连接状态为active（不阻塞UI）
    Future.microtask(() async {
      try {
        final tunnelRepository = _container.read(tunnelRepositoryProvider);
        await tunnelRepository.updateTunnelStatus(
          tunnelId: result.tunnelId,
          status: 'active',
        );
        print('✅ 数据库状态已更新为active: ${result.tunnelId}');
      } catch (e) {
        print('⚠️ 更新数据库状态失败: $e');
      }
    });

    // 5. 异步保存连接状态（不阻塞UI）
    Future.microtask(() async {
      await _saveConnectionStates();
    });

    print('🟢 TCP隧道连接已建立: ${result.tunnelId}');
    return tunnelData;
  }

  /// 断开隧道
  Future<void> disconnectTunnel(String tunnelId) async {
    print('🔴 开始断开隧道: $tunnelId');
    
    // 1. 仅使用简化Go实现断开TCP连接
    try {
      final success = await SimpleTunnelService.disconnectTunnel(tunnelId);
      if (success) {
        print('🚀 Go TCP隧道连接已断开: $tunnelId');
      } else {
        print('⚠️ Go TCP隧道断开失败: $tunnelId');
      }
    } catch (e) {
      print('❌ Go断开隧道异常: $e');
    }
    
    // 2. 🔥🔥🔥 立即从持久化状态中移除这个tunnelId（避免时序问题）
    // 关键修复：不要调用 _saveConnectionStates()（它会重新读取Go层状态）
    // 而是直接从持久化列表中移除这个tunnelId
    try {
      final prefs = await SharedPreferences.getInstance();
      final activeConnections = prefs.getStringList('active_tunnel_connections') ?? [];
      activeConnections.remove(tunnelId);
      await prefs.setStringList('active_tunnel_connections', activeConnections);
      print('✅ 持久化状态已清除: $tunnelId (剩余: ${activeConnections.length} 个)');
    } catch (e) {
      print('❌ 清除持久化状态失败: $e');
    }
    
    // 3. 🔥🔥🔥 同步更新数据库连接状态为inactive（确保刷新前生效）
    // 之前是异步的（Future.microtask），导致刷新时服务端status可能还是'active'
    try {
      final tunnelRepository = _container.read(tunnelRepositoryProvider);
      await tunnelRepository.updateTunnelStatus(
        tunnelId: tunnelId,
        status: 'inactive',
      );
      print('✅ 数据库状态已同步更新为inactive: $tunnelId');
    } catch (e) {
      print('⚠️ 更新数据库状态失败: $e (不影响断开连接)');
    }
    
    print('🔴 断开隧道完成: $tunnelId');
  }

  /// 删除隧道
  Future<bool> deleteTunnel(String tunnelId) async {
    print('🗑️  删除隧道: $tunnelId');
    
    try {
      // 1. 先断开TCP连接（如果已连接）
      try {
        await SimpleTunnelService.disconnectTunnel(tunnelId);
        print('✅ TCP连接已断开: $tunnelId');
      } catch (e) {
        print('⚠️  断开TCP连接失败（可能未连接）: $e');
      }
      
      // 2. 调用API删除隧道
      final tunnelRepository = _container.read(tunnelRepositoryProvider);
      final apiResult = await tunnelRepository.deleteTunnel(tunnelId);
      
      if (apiResult.isFailure) {
        final failure = apiResult.failureOrNull!;
        print('❌ 删除隧道失败: ${failure.message}');
        throw Exception('删除隧道失败: ${failure.message}');
      }
      
      print('✅ 隧道已从服务器删除: $tunnelId');
      
      // 3. 清理本地连接状态
      Future.microtask(() async {
        await _saveConnectionStates();
      });
      
      return true;
    } catch (e) {
      print('❌ 删除隧道异常: $e');
      return false;
    }
  }

  /// 重连现有隧道
  static Future<void> reconnectExistingTunnel({
    required String tunnelId,
    required String serverName,
    required String localHost,
    required String localPort,
  }) async {
    print('🔄 重连现有隧道: $tunnelId');
    
    // 仅使用简化Go实现重连，传递现有的隧道ID
    try {
      final success = await SimpleTunnelService.createTunnel(
        serverName: serverName,
        localHost: localHost,
        localPort: localPort,
        tunnelId: tunnelId, // 使用现有的隧道ID
        onStateChange: (state, message) {
          print('🔄 Go重连状态变化通知: $state - $message');
        },
        onError: (error) {
          print('❌ Go重连错误通知: $error');
        },
      );
      
      if (!success.success) {
        throw Exception('Go隧道重连失败: ${success.error}');
      }
      
      print('🚀 使用简化Go实现重连隧道: $tunnelId');
    } catch (e) {
      print('❌ Go重连失败: $e');
      throw Exception('Go隧道重连失败: $e');
    }
    
    print('✅ 隧道重连成功: $tunnelId');
  }

  /// 获取TCP连接状态
  bool isTunnelConnected(String tunnelId) {
    // 仅使用简化Go实现检查连接状态
    return SimpleTunnelService.isTunnelConnected(tunnelId);
  }
  
  /// 获取所有活跃的TCP连接
  List<String> getActiveTunnelConnections() {
    // 仅使用简化Go实现获取活跃连接
    return SimpleTunnelService.getActiveTunnels();
  }

  /// 保存连接状态到本地存储
  static Future<void> _saveConnectionStates() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      
      // 获取活跃连接
      final activeConnections = SimpleTunnelService.getActiveTunnels();
      
      await prefs.setStringList('active_tunnel_connections', activeConnections);
      print('💾 已保存连接状态: ${activeConnections.length} 个活跃连接 (Go 实现)');
    } catch (e) {
      print('❌ 保存连接状态失败: $e');
    }
  }

  /// 从本地存储加载连接状态
  static Future<List<String>> _loadConnectionStates() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      return prefs.getStringList('active_tunnel_connections') ?? [];
    } catch (e) {
      print('❌ 加载连接状态失败: $e');
      return [];
    }
  }

  /// 检查隧道是否持久连接
  Future<bool> isTunnelConnectedPersistent(String tunnelId) async {
    // 首先检查实际TCP连接
    if (isTunnelConnected(tunnelId)) {
      return true;
    }
    
    // 然后检查持久化状态
    final savedConnections = await _loadConnectionStates();
    return savedConnections.contains(tunnelId);
  }

  /// 清理所有连接状态
  static Future<void> clearAllConnectionStates() async {
    try {
      // 断开所有Go连接
      final activeConnections = SimpleTunnelService.getActiveTunnels();
      for (final tunnelId in activeConnections) {
        await SimpleTunnelService.disconnectTunnel(tunnelId);
      }
      
      // 清理持久化状态
      final prefs = await SharedPreferences.getInstance();
      await prefs.remove('active_tunnel_connections');
      
      print('🧹 已清理所有连接状态');
    } catch (e) {
      print('❌ 清理连接状态失败: $e');
    }
  }

  /// 获取隧道列表
  Future<List<TunnelData>> getTunnels() async {
    final tunnelRepository = _container.read(tunnelRepositoryProvider);
    final apiResult = await tunnelRepository.getTunnels();
    
    if (apiResult.isFailure) {
      return [];
    }
    
    return apiResult.dataOrNull ?? [];
  }

  /// 创建模拟隧道数据（用于测试）
  static TunnelData createMockTunnelData({
    required String tunnelId,
    required String serverName,
    required String localHost,
    required String localPort,
  }) {
    final appConfig = AppConfig.instance;
    return TunnelData(
      tunnelId: tunnelId,
      serverName: serverName,
      localHost: localHost,
      localPort: localPort,
      tunnelHost: appConfig.tcpTunnelHost,
      tunnelPort: appConfig.tcpTunnelPort.toString(),
      publicPort: '8080',
      publicAddress: 'http://${tunnelId.split('-').first}.${appConfig.defaultDomain}',
      tunnelType: 'http',
    );
  }
}

/// 简化的 AuthService - 兼容性接口
class AuthService {
  static final _container = ProviderContainer();

  /// 初始化服务（兼容性方法）
  Future<void> initialize() async {
    // 新架构中初始化是自动的，这里保持兼容性
  }

  /// 发送验证码
  Future<String> sendVerificationCode(String phoneNumber) async {
    final authNotifier = _container.read(authProvider.notifier);
    await authNotifier.sendVerificationCode(phoneNumber);
    final state = _container.read(authProvider);
    
    // 检查是否有错误
    if (state.error != null) {
      throw Exception(state.error);
    }
    
    return state.verificationId ?? '';
  }

  /// 验证码登录
  Future<LoginResponse> verifyCodeAndLogin({
    required String phoneNumber,
    required String code,
    required String verificationId,
  }) async {
    final authNotifier = _container.read(authProvider.notifier);
    await authNotifier.verifyCodeAndLogin(
      phoneNumber: phoneNumber,
      code: code,
      verificationId: verificationId,
    );
    final state = _container.read(authProvider);
    
    // 检查登录是否成功
    if (state.error != null) {
      throw Exception(state.error);
    }
    
    if (state.user == null) {
      throw Exception('登录失败：用户信息为空');
    }
    
    // 简化返回，实际应该从state中构建完整的LoginResponse
    return LoginResponse(
      user: state.user!,
      token: 'token', // 这里应该从实际存储中获取
      expiresIn: 86400,
    );
  }

  /// 登出
  Future<void> logout() async {
    final authNotifier = _container.read(authProvider.notifier);
    await authNotifier.logout();
  }

  /// 验证Token
  Future<bool> validateToken() async {
    final authNotifier = _container.read(authProvider.notifier);
    // 这里需要实现Token验证逻辑
    return _container.read(isAuthenticatedProvider);
  }

  /// 获取用户信息
  Future<UserInfo?> getUserInfo() async {
    return _container.read(currentUserProvider);
  }

  /// 获取应用配置（兼容性方法）
  Future<Map<String, dynamic>?> getAppConfig() async {
    // 返回模拟配置
    return {
      'user_agreement_url': 'https://example.com/agreement',
      'privacy_policy_url': 'https://example.com/privacy',
    };
  }

  bool get isLoggedIn => _container.read(isAuthenticatedProvider);
  UserInfo? get currentUser => _container.read(currentUserProvider);

  void dispose() {
    _container.dispose();
  }
}
